<template>
  <div>
    <el-row type="flex" class="row-bg" :gutter="20">
      <!-- 右侧选题列表 -->
      <el-col :span="24">
        <el-card class="box-card tall-card">
          <!-- 标题和搜索栏 -->
          <div slot="header" class="clearfix">
            <div class="header-container">
              <span>选题列表</span>
              <!-- 搜索栏 -->
              <el-row :gutter="10" class="filter-container">
                <!-- 左侧搜索组件 -->
                <el-col :span="18">
                  <el-row :gutter="10" class="search-group">
                    <!-- 搜索框 -->
                    <el-col :span="6">
                      <el-input
                        v-model="searchQuery.keyword"
                        placeholder="搜索标题/描述"
                        clearable
                      />
                    </el-col>
                    <!-- 学院下拉框 -->
                    <el-col :span="6">
                      <el-select
                        v-model="searchQuery.college"
                        placeholder="选择学院"
                        clearable
                      >
                        <el-option
                          v-for="college in collegeOptions"
                          :key="college"
                          :label="college"
                          :value="college"
                        />
                      </el-select>
                    </el-col>
                    <!-- 人数下拉框 -->
                    <el-col :span="6">
                      <el-select
                        v-model="searchQuery.maxstudents"
                        placeholder="选择人数"
                        clearable
                      >
                        <el-option
                          v-for="num in maxStudentsOptions"
                          :key="num"
                          :label="`剩余${num}人`"
                          :value="num"
                        />
                      </el-select>
                    </el-col>
                    <!-- 状态下拉框 -->
                    <el-col :span="6">
                      <el-select
                        v-model="searchQuery.status"
                        placeholder="选择状态"
                        clearable
                      >
                        <el-option label="已发布" value="已发布"/>
                        <el-option label="已锁定" value="已锁定"/>
                      </el-select>
                    </el-col>
                  </el-row>
                </el-col>

                <!-- 右侧按钮 -->
                <el-col :span="6" class="button-group">
                  <el-button @click="handleReset" plain>重置</el-button>
                  <el-button type="primary" @click="handleSearch">搜索</el-button>
                  <el-button
                    v-if="isAdmin"
                    type="success"
                    @click="handleAddTopic"
                  >添加选题
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 表格部分 -->
          <el-table
            :data="topicList"
            stripe
            style="width: 100%"
            v-loading="loading"
            :fit="true"
          >
            <!-- 教师ID显示 -->
            <el-table-column
              prop="submitterId"
              label="教师ID"
              width="100"
              align="center"
            />
            <el-table-column
              prop="title"
              label="标题"
              min-width="160"
              show-overflow-tooltip
            />
            <el-table-column
              prop="description"
              label="描述"
              min-width="240"
              show-overflow-tooltip
            />
            <el-table-column
              prop="college"
              label="学院"
              width="110"
              align="center"
            />
            <el-table-column
              label="已选人数"
              width="90"
              align="center"
            >
              <template slot-scope="{ row }">
    <span :class="{ 'text-danger': (8 - row.maxstudents) === 8 }">
      {{ 8 - row.maxstudents }}/8
    </span>
              </template>
            </el-table-column>
            <el-table-column
              label="状态"
              width="90"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-tag :type="statusTagType(row.status)" effect="dark">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="发布时间"
              width="140"
              align="center"
            >
              <template slot-scope="{ row }">
                {{ formatTime(row.createtime) }}
              </template>
            </el-table-column>

            <el-table-column
              label="附件"
              width="90"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-link
                  v-if="row.attachment"
                  :href="row.attachment"
                  target="_blank"
                  type="primary"
                  :underline="false"
                >
                  <i class="el-icon-download"></i>
                </el-link>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200"
            align="center"
            >
            <template slot-scope="{ row }">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="mini"
                  plain
                  :disabled="row.maxstudents === 0 || row.status === '已锁定' || isCurrentUserSelected(row)"
                  @click="handleSelectTopic(row)"
                >
                <div class="button-content">
                  <div>选择</div>
                  <div class="remaining-text">剩余 {{ row.maxstudents }} 人</div>
                </div>
                </el-button>

                <el-button
                  v-if="isAdmin"
                  type="warning"
                  size="mini"
                  plain
                @click="handleEditTopic(row)"
                >
                编辑
                </el-button>
              </div>
            </template>
            </el-table-column>
          </el-table>
          <EditTopicDialog
            :visible.sync="editDialogVisible"
            :topic="selectedTopic"
            @refresh="loadTopics"
          />
          <!-- 分页 -->
          <el-pagination
            class="pagination"
            @current-change="handlePageChange"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            layout="total, prev, pager, next, jumper"
          />
        </el-card>
        <!-- 添加对话框模板 -->
        <el-dialog :visible.sync="addDialogVisible" title="添加选题">
          <el-form :model="newTopic">
            <el-form-item label="标题" required>
              <el-input v-model="newTopic.title"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="newTopic.description" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="学院" required>
              <el-input v-model="newTopic.college"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmAdd">确定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import EditTopicDialog from './EditTopicDialog.vue';

export default {
  components: { EditTopicDialog },
  data() {
    return {
      addDialogVisible: false,
      newTopic: { title: '', description: '', college: '' },
      editDialogVisible: false,
      selectedTopic: {},
      isAdmin: localStorage.getItem('role') === '超级管理员', // 从本地存储获取角色
      searchQuery: {
        keyword: '', // 合并标题、描述、教师ID的模糊搜索
        // title: '',
        college: '',
        status: '',
        maxstudents: ''
      },
      collegeOptions: [], // 从后端获取
      maxStudentsOptions: [], // 从后端获取
      topicList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  created() {
    this.loadTopics();
    this.loadFilterOptions(); // 加载筛选选项
  },
  methods: {
    // 判断当前用户是否已选该选题
    isCurrentUserSelected(row) {
      const userId = localStorage.getItem('userid');
      try {
        const selected = JSON.parse(row.selectedStudents || '[]');
        return selected.some(id => parseInt(id) === userId); // 处理字符串和数字类型
      } catch (e) {
        return false;
      }
    },
    // 编辑选题弹窗
    async handleEditTopic(row) {
      try {
        // 通过接口获取完整选题数据（包含 selected_students）
        const res = await this.$axios.get(`/topic/${row.topicid}`);
        this.selectedTopic = res.data;
        this.editDialogVisible = true;
      } catch (error) {
        this.$message.error('加载选题数据失败');
      }
    },
    // 添加选题弹窗
    handleAddTopic() {
      this.addDialogVisible = true;
    },
    async confirmAdd() {
      const userId = localStorage.getItem('userid');
      await this.$axios.post('/topic/add', {
        title: this.newTopic.title,
        description: this.newTopic.description,
        college: this.newTopic.college,
        submitterId: userId
      });
      this.loadTopics();
      this.addDialogVisible = false;
    },

    // 选择选题逻辑
    async handleSelectTopic(row) {
      const userId = localStorage.getItem('userid');
      // 检查已选数量
      const countRes = await this.$axios.get(`/topic/selected-count?userId=${String(userId)}`);
      console.log(11111111111111111111111111111);
      console.log(countRes);
      if (countRes.data >= 3) {
        this.$message.error('已达到最大可选数量');
        return;
      }

      // 调用接口
      try {
        const res = await this.$axios.post('/topic/select', {
          topicId: row.topicid, // 保持字符串（如果数据库字段是VARCHAR）
          userId: userId // 直接传递字符串
        });

        if (res.data === '选题成功') {
          this.$message.success('选题成功');
          this.loadTopics(); // 刷新列表
        } else {
          this.$message.error(res.data);
        }
      } catch (error) {
        this.$message.error('选题失败，请重试');
      }
    },


    // 重置方法
    handleReset() {
      this.searchQuery = {
        keyword: '',
        college: '',
        status: '',
        maxstudents: ''
      };
      this.pagination.currentPage = 1;
      this.loadTopics();
    },
    // 加载筛选选项
    async loadFilterOptions() {
      try {
        // 获取学院选项
        const collegeRes = await this.$axios.get('/topic/colleges');
        this.collegeOptions = collegeRes.data;

        // 获取最大人数选项
        const maxRes = await this.$axios.get('/topic/max-students');
        this.maxStudentsOptions = maxRes.data;
      } catch (error) {
        console.error('加载筛选选项失败:', error);
      }
    },

    // 时间格式化方法
    formatTime(isoTime) {
      if (!isoTime) return '';
      const date = new Date(isoTime);
      // 格式化为 yyyy-mm-dd 时:分
      return `${date.getFullYear()}-${this.pad(date.getMonth() + 1)}-${this.pad(date.getDate())} ${this.pad(date.getHours())}:${this.pad(date.getMinutes())}`;
    },
    // 补零函数
    pad(num) {
      return num.toString().padStart(2, '0');
    },

    // 加载选题数据
    async loadTopics() {
      this.loading = true;
      try {
        const params = { page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          ...this.searchQuery }; // 原有参数
        const response = await this.$axios.get('/topic/list', {params});
        // 强制重新渲染表格
        this.topicList = response.data.list.map(item => ({ ...item }));
        this.pagination.total = response.data.total;
      } catch (error) {
        console.error('加载选题失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 处理搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.loadTopics();
    },
    // 处理分页
    handlePageChange(page) {
      this.pagination.currentPage = page;
      this.loadTopics();
    },
    // 状态标签样式
    statusTagType(status) {
      const map = {
        '已发布': 'success',
        '待审核': 'warning',
        '已锁定': 'danger'
      };
      return map[status] || 'info';
    }
  }
};
</script>

<style scoped>

/* 修改按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.el-button--primary.is-plain {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.el-button--primary.is-plain .remaining-text {
  color: #666;
}

.el-button--primary.is-plain:hover {
  background-color: #409EFF;
  color: white;
}

.el-button--primary.is-plain:hover .remaining-text {
  color: rgba(255,255,255,0.8);
}

.el-button.is-disabled.is-plain .remaining-text {
  color: #c0c4cc;
}

/* 调整按钮最小宽度 */
.el-button--mini {
  min-width: 85px;
  padding: 6px 8px;
  line-height: 1.4;
}
.button-content {
  line-height: 1.2;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.remaining-text {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
  font-weight: normal;
}

/* 调整按钮最小宽度 */
.el-button--mini {
  min-width: 80px;
  padding: 5px 8px;
}

/* 禁用状态的文字颜色 */
.el-button.is-disabled .remaining-text {
  color: #c0c4cc;
}

.text-danger {
  color: #F56C6C;
  font-weight: bold;
}

/* 调整布局样式 */
.header-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.filter-container {
  margin-top: 10px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 调整表格间距 */
.el-table {
  margin-top: 20px;
}

.el-table__body-wrapper {
  overflow-x: hidden !important;
}

.el-table th,
.el-table td {
  padding: 8px 0 !important;
}

/* 移除卡片内边距 */
.el-card__body {
  padding: 0 20px 20px 20px !important;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
}

.el-table {
  table-layout: fixed; /* 固定表格布局 */
}

.el-table::before {
  height: 0; /* 移除默认的伪元素线条 */
}

.el-table__body-wrapper {
  overflow-x: hidden; /* 隐藏横向滚动条 */
}

.el-card__body {
  padding: 15px; /* 减少卡片内边距 */
}

.tall-card {
  min-height: auto; /* 移除固定高度 */
  height: calc(100vh - 120px); /* 根据视口高度自适应 */
}

.el-col-18 {
  padding-left: 10px !important; /* 减少列间距 */
}

.filter-row .el-col {
  margin-bottom: 8px; /* 调整筛选栏间距 */
}

.action-btn {
  width: 100%;
}

.filter-container {
  padding: 10px;
}

.search-btn {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.mb-10 {
  margin-bottom: 10px;
}

.mb-20 {
  margin-bottom: 20px;
}

.tall-card {
  min-height: 600px;
}
</style>
